package cn.shentianlan.utils;

import cn.shentianlan.domain.DeviceData;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

public class RedisUtil{
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 在当前list集合的尾部添加数据
     * @param key
     * @param value
     * @return
     */
    public long rightPush(String key,Object object) throws JsonProcessingException {
        String objectString  = JsonUtils.ObjectToString(object);
        ListOperations listOperations = redisTemplate.opsForList();
        Long result = listOperations.rightPush(key,objectString);
        return result;
    }

    /**
     * 遍历list集合的所有数据
     * @param key
     */
    public  String range(String key) throws JsonProcessingException {
        ListOperations listOperations = redisTemplate.opsForList();
        List<String> result = listOperations.range(key, 0, -1);
        List<DeviceData> list = new ArrayList<DeviceData>();
        for (String deviceData:result) {
            list.add(JsonUtils.jsonToPojo(deviceData,DeviceData.class));
        }
        if (result.size() == 0){
            return null;
        }
        return JsonUtils.ObjectToString(list);
    }

    public  void push(String key,List<?> list) throws JsonProcessingException {
        ListOperations listOperations = redisTemplate.opsForList();
        if (list==null&&list.size()==0){
            return;
        }
        for (Object object:list) {
            rightPush(key,object);
        }
    }
}
